package m.fun.action;

import m.appserver.AuthInfoUtil;
import m.base.util.LevelUtil;
import m.base.util.PowerUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.common.model.util.QueryOrder;
import m.fun.model.BeginDetail;
import m.fun.model.BeginInfo;
import m.fun.model.BuildOrderModel;
import m.fun.service.BeginInfoService;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.Element;
import m.html.element.Text;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.form.*;
import m.html.list.*;
import m.store.action.GuestInfoAction;
import m.store.action.OrderModelAction;
import m.store.action.SaleInfoAction;
import m.store.action.StockInfoAction;
import m.store.model.OrderModel;
import m.store.service.StoreNumberService;
import m.system.util.DateUtil;
import m.system.util.JSONMessage;
import m.system.util.StringUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@ActionMeta(name = "fun/beginInfo")
public class BeginInfoAction extends OrderModelAction {
    private BeginInfo model;
    private List<BeginDetail> detailList;

    /**
     * 保存
     */
    @RequestMeta(transaction = true,logTitle = "期初信息",logDescription = "保存期初信息")
    public JSONMessage doSave() throws Exception {
        model.setStore(PowerUtil.getSessionStore(true));
        model.setInputUser(PowerUtil.getSessionUser(true));
        model.setInputDate(new Date());
        String msg=getService(BeginInfoService.class).save(model,detailList);
        return new JSONMessage(0,msg)
                .push("model", model);
    }
    @RequestMeta(logTitle = "期初信息",logDescription = "生成期初入库")
    public JSONMessage doSaveStockAndSale() throws Exception {
        getService(BeginInfoService.class).saveStockAndSale(model.getOid(),PowerUtil.getSessionUserOid());
        return new JSONMessage(0,"生成成功");
    }

    /*
     * 编辑期初
     */
    public VueResult toEdit() throws Exception {
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*","guest.*","inputUser.realname");
            PowerUtil.verifyStoreData(model.getStore().getOid());
            detailList=ModelQueryList.getModelList(BeginDetail.class,new String[]{"*","goods.*"},null,
                QueryCondition.eq("begin.oid",model.getOid()), QueryOrder.asc("oid"));
        }else{
            model=new BeginInfo();
            model.setOrderNo(StoreNumberService.getNextBeginNumber());
            model.setGuest(PowerUtil.getSelfGuestInfo());
            model.setStatus(OrderModel.Status_Register);
            model.setInputUser(PowerUtil.getSessionUser(true));
            model.setInputDate(new Date());
            model.setBeginDate(DateUtil.format("2023","yyyy"));
            detailList=new ArrayList<>();
        }
        boolean edit=OrderModel.Status_Register.equals(model.getStatus());
        boolean check=OrderModel.Status_Check.equals(model.getStatus())&&PowerUtil.hasPower(PowerUtil.Stock);

        ModelForm form = new ModelForm("期初入库信息");
        form.addItem(
            FormHtml.inputStyle("期初单号","{{model.orderNo}}"),
            FormHtml.inputStyle("客户", "<a @click=\"viewGuest\">{{model.guest.name}}</a>").setSpan(2),
            FormHtml.inputStyle("登记人","{{model.inputUser.realname}} {{model.inputDate}}"),
            FormHtml.inputStyle("期初金额","<b>{{detailList.length?formatNumber(model.beginAmount,'#,##0.00'):'请添加明细'}}</b>"),
            FormHtml.inputStyle("期初日期","{{formatDate(model.beginDate,'yyyy-MM-dd')}}"),
            FormInput.textarea("备注","model.remark").setSpan(3).setEdit(edit||check)
        )
        .addData("model",model).addData("detailList",new ArrayList<>())
        .addButton(
            edit? FormButton.pri("保存","doSave"):null
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doSave",actionUrl("doSave"),"{model:this.model,detailList:this.detailList}")
                .fillData("model").success("backFlag"),
            FormEvent.toModal("viewGuest",actionUrl(GuestInfoAction.class,"toView"),"{model:{oid:this.model.guest.oid}}",1300)
        );
        TableForm form1=new TableForm("期初商品").setEdit(edit,true,"{repository:"+getDefRepParam()+",goods:{},preferential:0}",false);
        form1.setData("detailList",detailList)
        .addMethod(
            FormEvent.custom("editRowAfter(item)",
            "item.amount=this.roundNumber((item.price||0)*(item.num||0)-(item.preferential||0),2);" +
                "item.preferentialPrice=this.roundNumber(item.amount/(item.num||1),2);"
            ),
            FormEvent.custom("editDataAfter",
            "var sum=0.0;" +
                "for(var i=0;i<this.detailList.length;i++){" +
                " sum+=(this.detailList[i].amount||0);" +
                "}" +
                "this.model.beginAmount=this.roundNumber(sum,2);"
            )
        )
        .setEditRowConfirm("editRowAfter")
        .setRowChangeAfter("editDataAfter")
        .addColumn(
            TableColumn.index("序号"),
            TableColumn.text("仓库","repository.oid",100)
                .setShow(new Text("{{dict('m.store.model.RepositoryInfo:"+PowerUtil.getSessionStoreOid()+"',text)}}"))
                .setEdit(TableEdit.select("m.store.model.RepositoryInfo:"+PowerUtil.getSessionStoreOid())),
            TableColumn.text("商品","goods.name",200)
                .setEdit(TableEdit.selectOneModel("'action/store/storeGoods/selectOneStoreGoods'",1100,"goods","name")),
            TableGroup.ins("入库",
                TableColumn.number("单价","price",100).isSum(false)
                    .setEdit(TableEdit.number()),
                TableColumn.number("数量","num",80,"#,##0")
                    .setEdit(TableEdit.number("#,##0",0)),
                TableColumn.number("总优惠","preferential",100)
                    .setEdit(TableEdit.number())
            ),
            TableGroup.ins("优惠后",
                TableColumn.number("单价","preferentialPrice",100).isSum(false)
                    .setEdit(Element.tag("div").E("{{formatNumber((editRecord.price*editRecord.num-editRecord.preferential)/editRecord.num,'#,##0.00')}}")),
                TableColumn.number("金额","amount",100)
                    .setEdit(Element.tag("div").E("{{formatNumber(editRecord.price*editRecord.num-editRecord.preferential,'#,##0.00')}}"))
            ),
            TableColumn.text("备注","remark",150)
                .setEdit(TableEdit.input())
        );

        VueFormResult result=new VueFormResult();
        return result.addForm(form).addForm(form1);
    }
    public VueResult toView() throws Exception {
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*","guest.*","inputUser.realname");
            PowerUtil.verifyStoreData(model.getStore().getOid());
        }else{
            throw AuthInfoUtil.noPowerException;
        }
        ModelForm form = new ModelForm("期初信息",3);
        form.addItem(
            FormHtml.inputStyle("期初单号","{{model.orderNo}}"),
            FormHtml.inputStyle("客户", "<a @click=\"viewGuest\">{{model.guest.name}}</a>").setSpan(2),
            FormHtml.inputStyle("期初金额","<b>{{formatNumber(model.beginAmount,'#,##0.00')}}</b>"),
            FormHtml.inputStyle("期初日期","{{formatDate(model.beginDate,'yyyy-MM-dd')}}"),
            FormHtml.inputStyle("登记人","{{model.inputUser.realname}} {{formatDate(model.inputDate,'yyyy-MM-dd HH:mm')}}"),
            FormHtml.inputStyle("备注","{{model.remark}}").setSpan(3)
        )
        .addData("model",model)
        .addMethod(
            FormEvent.toModal("viewGuest",actionUrl(GuestInfoAction.class,"toView"),"{model:{oid:this.model.guest.oid}}",1300)
        );
        LoadPage detailPage=new LoadPage("loadDetailPage",actionUrl(BeginDetailAction.class,"recordList"),"{params:{'begin.oid':this.model.oid}}")
            .setMounted("this.loadDetailPage();");
        VueFormResult result=new VueFormResult();
        result.addForm(form).addForm(detailPage);
        return result;
    }
    /*
     * 我的期初登记列表
     */
    public VueResult inputList() throws Exception {
        VueListResult result=getVueListResult("期初入库登记", BeginInfo.class,actionUrl("inputList"));
        result.addQueryFields("buildStatus","status");
        result.addCol(toIndexColumn());
        result.addCol(toLinkColumn("期初单号", "orderNo", 120, true,
            new ListEvent(actionUrl("toView"), EventType.MODAL,1200)
                .addParam("model.oid","oid")
        ));
        result.addCol(toTextColumn("客户", "guest.name", 150, true));
        result.addCol(toNumberColumn("期初金额", "beginAmount", 100, true));
        result.addCol(toDateColumn("期初日期", "beginDate", 100, true));
        result.addCol(toTextColumn("备注","remark",150,true));
        result.addCol(toLinkColumn("入库订单", "stock.orderNo", 120, true,
            new ListEvent(actionUrl(StockInfoAction.class,"toView"), EventType.MODAL,1200)
                .addParam("model.oid","stock.oid")
        ));
        result.addCol(toTextColumn("登记人", "inputUser.realname", 100, true));
        result.addCol(toDateTimeColumn("录入时间", "inputDate", 130, true));
        result.addCol(toSpaceColumn("操作", 140,
            ListElement.test("record.status=='"+ OrderModel.Status_Register+"'",
                ListButton.page("修改", ButtonType.PRIMARY,actionUrl("toEdit"), SuccessMethod.REFRESH)
                    .addParam("model.oid","oid")
            ),
            ListElement.test("record.buildStatus=='"+ BuildOrderModel.Build_No+"'",
                ListButton.ajax("生成库存", ButtonType.SUCCESS,actionUrl("doSaveStockAndSale"), SuccessMethod.REFRESH)
                    .addParam("model.oid","oid").setConfirm("生成期初入库，请确认操作！")
            )
        ).setFixed(Align.RIGHT));
        result.addButton(
            ListButton.page("登记期初入库", ButtonType.PRIMARY,actionUrl("toEdit"), SuccessMethod.REFRESH)
        );
        result.setDefaultSearchNum(3);
        result.addSearch(ListSearch.field("期初单号","orderNo",SearchType.STR_MANY_LIKE));
        result.addSearch(ListSearch.field("期初金额","beginAmount",SearchType.NUMBER_RANGE));
        result.addSearch(ListSearch.field("入库订单","stock.orderNo",SearchType.STR_MANY_LIKE));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("inputUser.oid", PowerUtil.getSessionUser(true).getOid()));
        return result;
    }
    public BeginInfo getModel() {
        return model;
    }

    public void setModel(BeginInfo model) {
        this.model = model;
    }

    public List<BeginDetail> getDetailList() {
        return detailList;
    }

    public void setDetailList(List<BeginDetail> detailList) {
        this.detailList = detailList;
    }
}
